<template>
  <div v-if="status == 0">
    <div v-for="(el,idx) in testList">
      <TestItem :id="'item_'+idx" :question=el :index=idx :selected=answerList[idx].r @sendOptionClick='optionClick' />
    </div>
    <div style="height: 94px;" />
    <div class="submitBtn" @click="submitClick">
      提交
    </div>
    <van-popup v-model="showExit" :close-on-click-overlay=false style="width: 80%;">
      <TestExit :time=timeCount :answerList=answerList @sendContinueClick="continueClick" @sendExitClick="exitClick" />
    </van-popup>
  </div>
  <div v-else>
    <TestResult :result=result :testList="testList" :passScore="passScore" @sendAgainClick='againClick'></TestResult>
  </div>
</template>

  <script>

    import {Popup, Toast} from 'vant'
    import TestAPI from '@/repo/api/test_api.js'
    import TestItem from './components/TestItem-m.vue'
    import TestResult from './components/TestResult-m.vue'
    import TestExit from './components/TestExit-m.vue'

    Vue.use(Popup);

  export default {
    metaInfo: {
      title: "房地产课程测试",
    },
    components: {
      TestItem,
      TestResult,
      TestExit
    },
    data() {
      return {
        //答题模式or结果模式 0为答题， 1位结果
        status: 0,
        timer: null,
        timeCount: 0,
        examId: 0,
        courseId: 0,
        testList: [],
        answerList: [],
        result: {},
        //退出弹出层
        showExit: false,
        passScore: 0,
        testTitle: ''
      }
    },
    beforeDestroy() {
      this.clearTimer();
      window.onpopstate = () => {};
      window.name = ""
    },
    created() {
      if (window.name == "") {
        console.log("首次被加载");
        window.name = "isReload";
        history.pushState(null, null, document.URL);
      } else if (window.name == "isReload") {
        console.log("页面被刷新");
      };
      setTimeout(() => {
        window.onpopstate = this.popstate;
      }, 1000)
    },
    mounted() {
      this.examId = this.$route.params.examId
      this.courseId = this.$route.params.courseId
      this.loadTest()
    },
    methods: {
      popstate(e) {
        let that = this
        if (that.status == 0) {
          that.clearTimer()
          that.showExit = true;
        } else {
          that.$router.go(-1)
        }
      },
      //测试点击
      optionClick(el, index) {
        this.answerList[index]['r'] = el.selectName;
        let list = [];
        list.push(...this.answerList)
        this.answerList = list;
      },
      //提交按钮点击
      submitClick() {

        for (var index = 0; index < this.answerList.length; index++) {
          let answer = this.answerList[index]
          if (!answer.r) {
            Toast('测试题未完成')
            let element = document.querySelector(`#item_${index}`);
            let targetTop = element.offsetTop;
            window.scrollTo({
              top: targetTop,
              behavior: "smooth"
            });
            return
          }
        }
        this.clearTimer()
        this.submitTest()

      },
      //完成测试后点击再次测试
      againClick() {
        this.timeCount = 0
        this.clearTimer()
        this.startTimer()
        this.answerList = this.testList.map((item) => {
          return {
            'q': item.id
          }
        })
        this.status = 0
      },
      //中途退出点击继续测试
      continueClick() {
        this.showExit = false
        history.pushState(null, null, document.URL);
        this.clearTimer()
        this.startTimer()
      },
      //中途退出测试
      exitClick() {
        this.showExit = false
        window.onpopstate = () => {};
        this.$router.go(-1)
      },
      //启用定时器
      startTimer() {
        this.timer = setInterval(() => {
          this.timeCount++
        }, 1000);
      },
      //关闭定时器
      clearTimer() {
        clearInterval(this.timer)
      },
      //获取测试题
      loadTest() {
        TestAPI.getTestList(this.examId, this.courseId).then((result) => {
          this.passScore = result.responseData.passScores
          this.testList = result.responseData.questionList
          this.testTitle = result.responseData.title
          this.answerList = this.testList.map((item) => {
            return {
              'q': item.id
            }
          })
          this.startTimer()
        })
      },
      //提交测试题
      submitTest() {
        TestAPI.submitTest(this.examId, this.courseId, this.answerList, this.timeCount).then((result) => {
          console.log(result)
          this.result = result.responseData
          this.status = 1;
          this.hftRecord(result.responseData);
        })
      },

      hftRecord(data = {}) {
        if (!window.hasOwnProperty('zshft')) return;
        let params = {
          subjectId: this.courseId,
          subjectName: this.$store.getters["courseInfo/courseTitle"],
          assessmentId: this.examId,
          assessmentName: this.testTitle, // 测评名称
          scoreObtained: data.ext1,  // 测评所得分数
          isPass: data.examResult == 1 ? 1: 2 // 是否通过（1为通过 2为未通过）
        };
        window.zshft.onJsAssessmentEUResult(JSON.stringify(params));
      }
    },
  }
</script>

<style scoped>
  .submitBtn {
    position: fixed;
    bottom: 24px;
    left: 16px;
    right: 16px;
    background-color: #1286F7;
    height: 46px;
    border-radius: 23px;
    font-size: 18px;
    font-weight: bold;
    color: white;
    line-height: 46px;
    text-align: center;
  }
</style>
